package com.feiyisys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feiyisys.dto.ActivityResponseDTO;
import com.feiyisys.dto.FavoriteActivityResponseDTO;
import com.feiyisys.entity.Activity;
import com.feiyisys.entity.FavoriteActivity;
import com.feiyisys.mapper.FavoriteActivityMapper;
import com.feiyisys.service.FavoriteActivityService;
import com.feiyisys.service.ActivityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import jakarta.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户收藏活动记录表 服务实现类
 * </p>
 *
 * @author wq
 * @since 2025-10-10
 */
@Service
public class FavoriteActivityServiceImpl extends ServiceImpl<FavoriteActivityMapper, FavoriteActivity> implements FavoriteActivityService {

    @Resource
    private ActivityService activityService;

    @Override
    public boolean addFavorite(Long userId, Long activityId) {
        Assert.notNull(userId, "用户ID不能为空");
        Assert.notNull(activityId, "活动ID不能为空");

        Activity activity = activityService.getById(activityId);
        Assert.notNull(activity, "活动不存在或已删除");

        LambdaQueryWrapper<FavoriteActivity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FavoriteActivity::getUserId, userId)
                .eq(FavoriteActivity::getActivityId, activityId);

        long count = this.count(wrapper);
        if (count > 0) {
            throw new IllegalArgumentException("您已收藏该活动");
        }

        FavoriteActivity favorite = new FavoriteActivity();
        favorite.setUserId(userId);
        favorite.setActivityId(activityId);
        favorite.setCreateTime(new Date());

        return this.save(favorite);
    }

    @Override
    public boolean removeFavorite(Long userId, Long activityId) {
        Assert.notNull(userId, "用户ID不能为空");
        Assert.notNull(activityId, "活动ID不能为空");

        LambdaQueryWrapper<FavoriteActivity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FavoriteActivity::getUserId, userId)
                .eq(FavoriteActivity::getActivityId, activityId);

        return this.remove(wrapper);
    }

    @Override
    public boolean isFavorite(Long userId, Long activityId) {
        if (userId == null || activityId == null) {
            return false;
        }
        LambdaQueryWrapper<FavoriteActivity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FavoriteActivity::getUserId, userId)
                .eq(FavoriteActivity::getActivityId, activityId);
        return this.count(wrapper) > 0;
    }

    @Override
    public IPage<FavoriteActivityResponseDTO> getFavoriteActivities(Long userId, Long current, Long size) {
        Assert.notNull(userId, "用户ID不能为空");
        Page<FavoriteActivity> page = new Page<>(current, size);
        LambdaQueryWrapper<FavoriteActivity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FavoriteActivity::getUserId, userId)
                .orderByDesc(FavoriteActivity::getCreateTime);

        IPage<FavoriteActivity> favoritePage = this.page(page, wrapper);

        List<Long> activityIds = favoritePage.getRecords().stream()
                .map(FavoriteActivity::getActivityId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        Map<Long, ActivityResponseDTO> activityMap = new HashMap<>();
        if (!activityIds.isEmpty()) {
            for (Long activityId : activityIds) {
                try {
                    ActivityResponseDTO activity = activityService.getActivityById(activityId);
                    activityMap.put(activityId, activity);
                } catch (IllegalArgumentException ignored) {
                    // 活动不存在时忽略
                }
            }
        }

        List<FavoriteActivityResponseDTO> records = favoritePage.getRecords().stream()
                .map(record -> {
                    ActivityResponseDTO activity = activityMap.get(record.getActivityId());
                    if (activity == null) {
                        return null;
                    }
                    FavoriteActivityResponseDTO dto = new FavoriteActivityResponseDTO();
                    dto.setId(record.getId());
                    dto.setUserId(record.getUserId());
                    dto.setActivityId(record.getActivityId());
                    dto.setCreateTime(record.getCreateTime());
                    dto.setActivity(activity);
                    return dto;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        Page<FavoriteActivityResponseDTO> dtoPage = new Page<>(current, size, favoritePage.getTotal());
        dtoPage.setPages(favoritePage.getPages());
        dtoPage.setRecords(records);
        return dtoPage;
    }
}
